<!--批量活动审核及下发 只有厂端有-->
<template>
  <div>
    <TopFilter ref="topfilter" :list="topFilterList" :cols="4" labelWidth="110" :collapse="true" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      :isExportExcel="false"
      exportFileName="服务活动管理.xlsx"
      :onCalcExportData="handleExportFun"
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      datakey="records"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
    >
      <template slot="controls" >
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button>
        <multiuse-button size="small" type="primary" icon="el-icon-check" :click="xiafa.bind()" :disabled="disableds">发布</multiuse-button>


        <multiuse-button type="primary" :click="exportHandle.bind(this)">导出</multiuse-button>
      </template>
    </FilterTable>
    <Drawer :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <add :row="formData" :maId="maId" @close="closeHandler" :handleType="handleType" />
    </Drawer>
    <Drawer :visible.sync="visibleNewCar" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addNewCar :row="formData" :maId="maId" @close="closeHandler" :handleType="handleType" />
    </Drawer>
     <Drawer :visible.sync="visibleDetail" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <detail :row="formData" :maId="maId" @close="closeHandler" :handleType="handleType" />
    </Drawer>
  </div>
</template>

<script>
import { exportExcelFile } from '@/utils/index';
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import add from './add';
import addNewCar from './addNewCar';
import detail from './detail';
import { isEmpty } from '@/utils/utils';
import { listRecord, getAllUser,changeStatus, saveStop, piliangxiafa,changeDate, exportMaRecord,exporturl } from '@/api/repair/batchEventManagement/activityDistribution';
import { arrayObjDeWeight } from '@/utils';
import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';
import { getAppId } from '@/assets/js/auth';


export default {
  name: 'addItem',
  mixins: [dictionary, dealerMixin],
  data() {

    // this.BaseTable = null;
    // this.conf = { add: '新增', edit: '编辑' };
    return {
      BaseTable :null,
      conf : { add: '新增', edit: '编辑',show: '' },
      dataList: [],
      disableds: true,
      selectedRows: [],
      topFilterList: this.createTopFilterList(),
      visible: false,
      visibleNewCar: false,
      visibleDetail: false,
      fetchApi: listRecord,
      dialogTitle: '',
      fetchParams: { xhrAbort: true },
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      maId: ''
    };
  },
  components: {
    add,
    detail,
    addNewCar
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initSelect();
    this.spliceCloum();
  },
  methods: {
     //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      console.log(this.selectedRows);
    },
    async exportHandle() {

      const [err, params] = await this.$refs.topfilter.GET_FORM_DATA();

      await this.downHandleFile(exportMaRecord, params, '服务活动管理');
    },

    // 导出处理函数
    handleExportFun(row) {
      row.maStatus = this.createDictText(row.maStatus, 1014);
      row.dataSource = this.createDictText(row.dataSource, 1015);
      row.ifOta = this.createDictText(row.ifOta, 1004);

      row.maLevel = this.createDictText(row.maLevel, 1017);

      let ifPartName = row.ifPart == 10041001 ? '已满足' : '未满足';

      let ifTechName = row.ifTech == 10041001 ? '已满足' : '未满足';

      let ifClaimName = row.ifClaim == 10041001 ? '已满足' : '未满足';

      row.ifClaim = ifClaimName;

      row.ifTech = ifTechName;

      row.ifPart = ifPartName;
    },

    async initSelect() {

      this.getAllUsers(this.columns, ['maBy'], 'table');
    },

     //批量下发
    async xiafa() {
      if (this.selectedRows.length > 0) {

        // debugger
        let ids = '';
        let eDate = '';
        let maStatus = 0;
        this.selectedRows.map((x) => {
          ids += x.maId + ',';
          eDate = x.eDate;
          maStatus = x.maStatus;
        });


      //获取当前时间
      var date = new Date();
      var year = date.getFullYear(); //月份从0~11，所以加一
      var dateArr = [date.getMonth() + 1,date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds()];
      for(var i=0;i<dateArr.length;i++){
        if (dateArr[i] >= 1 && dateArr[i] <= 9) {
            dateArr[i] = "0" + dateArr[i];
        }
      }
      var strDate = year+'-'+dateArr[0]+'-'+dateArr[1]+' '+dateArr[2]+':'+dateArr[3]+':'+dateArr[4];


        console.log("ids:"+ids+"eDate:"+eDate,99999999,strDate);

        if(maStatus == 10141002){//待下发

            if(eDate>=strDate){//活动结束日期大于当前时间
            const res = await piliangxiafa({ ids});
              this.$notify.success({ title: '提示信息', message: '发布成功' });
              this.fetchParams = { ...this.fetchParams };//更新

            }else{
               this.$notify.warning({ title: '提示信息', message: '活动截止日期小于当前日期，不能发布' });
                            this.fetchParams = { ...this.fetchParams };//更新


            }
        }else if(maStatus == 10141003){//10141003
             this.$notify.warning({ title: '提示信息', message: '该活动已发布！' });
                          this.fetchParams = { ...this.fetchParams };//更新



        }else if(maStatus == 10141005){//10141005
             this.$notify.warning({ title: '提示信息', message: '该活动已作废！' });
                          this.fetchParams = { ...this.fetchParams };//更新



        }else{
             this.$notify.warning({ title: '提示信息', message: '该活动已关闭！' });
                          this.fetchParams = { ...this.fetchParams };//更新

        }
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行发布！' });
      }
    },
    spliceCloum() {
      let appId = getAppId().toLowerCase();
      if (appId == 'arcfox') {
        this.columns.splice(7, 1);
      }
    },
    createTableColumns() {
      return [

        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 150,
          render: props => {
            let obj = props.row;

            let dataSource = isEmpty(obj['dataSource']) ? '' : obj['dataSource'];
            let maStatus = isEmpty(obj['maStatus']) ? '' : obj['maStatus'];

            let rst = false;
            if (dataSource == '10151001' && maStatus == '10141001') {
              rst = true;
            }

            let editFlag = true;

            if (maStatus == '10141002' || maStatus == '10141004') {//待下发
              editFlag = false;
            }

            let closeFlag = false;
            if (maStatus == '10141005' || maStatus == '10141004') {//已作废

              closeFlag = true;
            }
             return (
              <div>
                <el-button size="mini" type="text" disabled={editFlag} onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
                <el-button size="small" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </el-button>
                <el-button size="small" type="text" disabled={closeFlag} onClick={() => this.changeStatusHandle(props.row)}>
                  关闭
                </el-button>
              </div>
            );
          }
        },

        {
          title: '状态',
          dataIndex: 'maStatus',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1014,[10141001, 10141006]),
          render: props => {
            return <span>{this.createDictText(props.row.maStatus, 1014)}</span>;
          }
        },

        {
          title: '活动编号',
          dataIndex: 'maNo',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '活动名称',
          dataIndex: 'maTitle',
          sorter: true,
          filter: true,
          filterType: 'input'
          // render: props => {
          //   return <span>{this.changgeDictYN(props.row.downTag)}</span>;
          // }
        },

        {
          title: '活动类型',
          dataIndex: 'maStrategy',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(5080),
          render: props => {
                    //     return <span>{this.createDictText(props.row.dataSource, 1015)}</span>;

            // let maStrategy = props.row.maStrategy == 50801002 ? '服务活动' : '技术活动';
            return <span>{this.createDictText(props.row.maStrategy, 5080)}</span>;
          }

        },

        {
          title: '活动开始日期',
          dataIndex: 'bDate',
          width: 150,
          sorter: true,
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '活动结束日期',
          dataIndex: 'eDate',
          // defaultEditable: true,
          // editable: true,
          editType: 'date-picker',
          width: 150,
          sorter: true,
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '发布日期',
          dataIndex: 'maDate',
          width: 150,
          sorter: true,
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '更新日期',
          dataIndex: 'updatedAt',
          width: 150,
          sorter: true,
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },

      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '活动编号',
          fieldName: 'maNo',
          placeholder: '活动编号...'
        },
        {
          type: 'INPUT',
          label: '活动名称',
          fieldName: 'maTitle',
          placeholder: '活动名称...'
        },

        {
          type: 'RANGE_DATE',
          label: '活动发布日期',
          dateType: 'daterange',

          style: { minWidth: '200px' },
          fieldName: 'maDate1|maDate2',
          rangeSeparator:'至'
        },
        {
          type: 'SELECT',
          label: '活动类型',
          fieldName: 'maStrategy',
          placeholder: '请选择',
          itemList: this.createDictList(5080) //待下发、已下发、已关闭展示
        },
        {
          type: 'SELECT',
          label: '活动状态',
          fieldName: 'maStatus',
          placeholder: '请选择',
          itemList: this.createDictList(1014, [10141001, 10141005,10141006]) //待下发、已下发、已作废展示
        }
      ];
    },
    isEdit(row) {},
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
     detailHandle(row) {
      this.maId = row['maId'];
      this.handleType = 'show';
       this.formData = row;
      this.dialogTitle = `${this.conf[this.handleType]}服务活动`;
      this.visibleDetail = true; //明细
    },
    addHandle() {
      this.handleType = 'add';
      this.formData = {};
      this.maId = '';
      this.showHandler();
    },
    editHandle(row) {
      this.maId = row['maId'];
      this.maStatus = row['maStatus'];
      this.handleType = 'edit';
      this.formData = row;
      if(this.maStatus=='10141004'){
        this.visibleNewCar = true;
        console.log(this.visibleNewCar,111,this.maStatus)
      }else{
        this.showHandler();
         console.log(this.visible,222,this.maStatus)

      }
    },

    changeStatusHandle(row){
     this.$confirm('您确定要关闭该活动吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await this.changeStatus(row);
          console.log('确定');
        })
        .catch(() => {
          console.log('取消');
        });
    },

    showHintDialog(row) {
      this.$confirm('您确定要关闭吗,关闭之后您不可再次操作？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await this.closeHandle(row);
          console.log('确定');
        })
        .catch(() => {
          console.log('取消');
        });
    },
    changeDateHintDialog(row) {
      if (moment(row.eDate) < moment(row.bDate)) {
        this.$notify.warning({ title: '提示信息', message: '活动截止日期不能小于开始日期' });
        return;
      }
      this.$confirm('您确定要修改时间吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await this.changeDateHandle(row);
          console.log('确定');
        })
        .catch(() => {
          console.log('取消');
        });
    },

    async changeDateHandle(row) {
      let res = await changeDate({ maId: row['maId'], eDate: moment(row['eDate']).format('YYYY-MM-DD HH:mm:ss') });

      if (res.resultCode == 200 && res.success == true) {
        this.fetchParams = Object.assign({}, this.fetchParams);
        this.$notify.success({ title: '提示信息', message: '操作成功' });
      } else {
        let errMsg = isEmpty(res.errMsg) ? '操作失败' : res.errMsg;

        this.$notify.error({ title: '提示信息', message: errMsg });
      }
    },

    async changeStatus(row) {
      let res = await changeStatus({ maId: row['maId']});

      if (res.resultCode == 200 && res.success == true) {
        this.fetchParams = Object.assign({}, this.fetchParams);
        this.$notify.success({ title: '提示信息', message: '操作成功' });
      } else {
        let errMsg = isEmpty(res.errMsg) ? '操作失败' : res.errMsg;

        this.$notify.error({ title: '提示信息', message: errMsg });
      }
    },

    async closeHandle(row) {
      let res = await saveStop({ maId: row['maId'] });

      if (res.resultCode == 200 && res.success == true) {
        this.fetchParams = Object.assign({}, this.fetchParams);
        this.$notify.success({ title: '提示信息', message: '操作成功' });
      } else {
        let errMsg = isEmpty(res.errMsg) ? '操作失败' : res.errMsg;

        this.$notify.error({ title: '提示信息', message: errMsg });
      }
    },
    changeHandle(val) {
      // val.bDate=moment(val['bDate']).format('YYYY-MM-DD')
      // val.eDate=moment(val['eDate']).format('YYYY-MM-DD')
      this.fetchParams = Object.assign({}, val);

      console.log(this.fetchParams);
    },
    showHandler(type = 0) {
      this.dialogTitle = `${this.conf[this.handleType]}服务活动`;
      if (type == 0) {
        this.visible = true;//新增，编辑
      // } else {
      //   debugger
      //    this.visibleDetail = true; //明细
      //    console.log(type+"type222222222");
      }
    },
    changgeDictYN(val) {
      console.log(val);
      if (val === 10041001) {
        return '是';
      } else {
        return '否';
      }
    },
    closeHandler(type) {
      this.visible = false;
      this.visibleDetail = false;
      this.visibleNewCar = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
